package StudyCode.summary.myfile;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ExtractAPKFile {
	public static void main(String[] argv) throws Exception {
		String apkPath = "www.tah1986.com";
		System.out.println(extractApks(apkPath));
	}

	private synchronized static List<String> extractApks(String apkPath) {
		List<String> ret = new ArrayList<String>();
		try {
			ZipFile zip = new ZipFile(apkPath);
			Enumeration<? extends ZipEntry> entries = zip.entries();
			while (entries.hasMoreElements()) {
				ZipEntry entry = entries.nextElement();
				if (entry.getName().endsWith(".apk")) {
					String tmpFilePath = Files.createTempFile("apktmp_", ".apk").toString();
					FileOutputStream fos = new FileOutputStream(tmpFilePath);
					BufferedInputStream is = new BufferedInputStream(
							zip.getInputStream(entry));
					int count = 0;
					int BUFFER = 2048;
					byte[] buf = new byte[BUFFER];
					count = is.read(buf, 0, BUFFER);
					while ((count = is.read(buf, 0, BUFFER)) != -1) {
						fos.write(buf, 0, count);
					}
					fos.flush();
					fos.close();

					JarFile jar = new JarFile(tmpFilePath);
					if (jar.getEntry("AndroidManifest.xml") != null)
						ret.add(tmpFilePath);
					jar.close();
				}
			}
		} catch (IOException e) {
			System.out.println("文件不存在或不是Apk文件");
		}
		return ret;
	}
}
